//
//  HttpMessage.cpp
//  myhttpserver
//
//  Created by tgy on 2018/3/19.
//  Copyright © 2018年 tgy. All rights reserved.
//

#include "HttpMessage.hpp"
#include <string>
#include "Utils.hpp"

HttpMessage::HttpMessage(){
    
    
}
HttpMessage::HttpMessage(std::string data){
    
    this->data = data;
}
HttpMessage::~HttpMessage(){
    
    
}

bool HttpMessage::parse(){
    
    std::vector<std::string> content;
    Utils::splitString(this->data, content, std::string("\r\n"));
    std::vector<std::string>::iterator p = content.begin();
    
    if (p != content.end()) {
        
        std::vector<std::string> firstline;
        Utils::splitString(*p, firstline, " ");
        
        if (firstline.size() != 3) {
            
            return false;
        }
        
        if (!setMethod(firstline[0])) {
            
            return false;
        }
        this->path = Utils::URLDecode(firstline[1]);
        this->httpVersion = firstline[2];
        
    }
    
    std::vector<std::string>::iterator end_p= --content.end();
    for (; end_p != p; end_p--) {
        
        size_t pos = (*end_p).find(":");
        if (pos != std::string::npos) {
            end_p++;
            break;
        }
    }
    if (end_p != p) {
        
        setHeadsFromVector(std::vector<std::string>(++p,end_p));
    }
    
    
    return true;
}

bool HttpMessage::setMethod(const std::string method){
    
    bool flag = false;
    for (int i = 0; i < METHODCOUNT; i++) {
        
        if (RequestMethod[i] == method) {
            
            flag = true;
            this->method = i;
            break;
        }
    }
    return flag;
}

//填充请求头
void  HttpMessage::setHeadsFromVector(const std::vector<std::string> headKeyValue){
    
    for (int i = 0; i < headKeyValue.size(); i++) {
        
        std::string keyValue = headKeyValue[i];
        
       size_t pos =  keyValue.find(":");
        std::string key = keyValue.substr(0,pos);
        std::string value = keyValue.substr(pos+1,keyValue.size());
        //去除前后空格a
        Utils::trimString(key);
        Utils::trimString(value);
        heads.insert(std::pair<std::string, std::string>( key , value));
    }
    
}


int HttpMessage::getMethod(){
    
    return method;
}

std::string HttpMessage::getPath(){
    
    return path;
}

void HttpMessage::addHeader(std::string key,std::string value){
    
    heads.insert(std::pair<std::string, std::string>(key,value));
}


void HttpMessage::setStauts(STAUTS stauts){
    
    this->stauts = stauts;
}





